package me.zhengjie.modules.system.rest;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.Clazzandstudent;
import me.zhengjie.modules.system.domain.Departmentteacher;
import me.zhengjie.modules.system.domain.Student;
import me.zhengjie.modules.system.domain.Teacher;
import me.zhengjie.modules.system.service.ClazzandstudentService;
import me.zhengjie.modules.system.service.DepartmentteacherService;
import me.zhengjie.modules.system.service.StudentService;
import me.zhengjie.modules.system.service.TeacherService;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.R;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "系统：上传")
@RestController
@RequestMapping("/api/upload")
@RequiredArgsConstructor
public class UploadController {

    private final DepartmentteacherService departmentteacherService;

    private final TeacherService teacherService;

    private final StudentService studentService;

    private final ClazzandstudentService clazzandstudentService;

    @ApiOperation("上传文件")
    @PostMapping(value = "/uploadFiles")
    public ResponseEntity<Object> uploadFiles(@RequestParam MultipartFile avatar){

        return new ResponseEntity<>(FileUtil.toFile(avatar), HttpStatus.OK);
    }

    @PostMapping("/importExcel")
    public ResponseEntity<Object>  importExcel(@RequestParam("file") MultipartFile file,@RequestParam("departmentId") Integer departmentId) {
        try {

            // 将文件内容读取到字节数组
            byte[] bytes = file.getBytes();
            List<String[]> data = readExcelFromBytes(bytes);
            data.remove(0);
            List<Map<String,Object>> mapList = new ArrayList<>();
            Integer initNumber = 0;

            Map<String,Object> mapMessage = new HashMap<>();

            List<Integer> statusList = new ArrayList<>();
            //验证逻辑
            for(String[] currentArr :data){
                initNumber++;
                Map<String,Object> map = new HashMap<>();
                Teacher teacher = new Teacher();
                if(!String.valueOf(currentArr[0]).equals("")){
                    teacher.setNumber(currentArr[0]);
                }

                if(!String.valueOf(currentArr[1]).equals("")){
                    teacher.setName(currentArr[1]);
                }
                if(!String.valueOf(currentArr[1]).equals("")){
                    teacher.setUsername(currentArr[1]);
                }

                if(!String.valueOf(currentArr[2]).equals("")){
                    teacher.setNickName(currentArr[2]);
                }

                if(!String.valueOf(currentArr[3]).equals("")){
                    teacher.setPassword(currentArr[3]);
                }

                if(!String.valueOf(currentArr[4]).equals("")){
                    teacher.setGender(currentArr[4]);
                }

                if(!String.valueOf(currentArr[5]).equals("")){
                    teacher.setPhone(currentArr[5]);
                }
                if(!String.valueOf(currentArr[6]).equals("")){
                    teacher.setEmail(currentArr[6]);
                }


                Map<String,Object> map1 = teacherService.checkTeacher(teacher);
//                map.put("status",map1.get("status"));

                if(String.valueOf(map1.get("status")).equals("1")){
                    statusList.add((Integer) map1.get("status"));
                }

                mapList.add(map1);
            }
            if(statusList.size()!=0){
                mapMessage.put("message","导入成功,但部分数据错误");
                mapMessage.put("mapList",mapList);
                mapMessage.put("status",1);
//                mapMessage.put("result",data);
//                return R.success(mapMessage);
//                System.out.println("==mapMessage=="+mapMessage);
                return new ResponseEntity<>(mapMessage, HttpStatus.valueOf(401));
            }
            for(String[] currentArr :data){


                    Teacher teacher = new Teacher();
                    teacher.setNumber(currentArr[0]);
                    teacher.setName(currentArr[1]);
                    teacher.setUsername(currentArr[1]);
                    teacher.setNickName(currentArr[2]);
                    teacher.setPassword(currentArr[3]);
                    teacher.setGender(currentArr[4]);
                    teacher.setPhone(currentArr[5]);
                    teacher.setEmail(currentArr[6]);
                    teacher.setEnabled(true);
                    Integer status = teacherService.create(teacher);



//                    if(status == -1){
//
//
//                        return R.error("邮箱重复");
//                    }
//                    if(status == -3){
//
//                        return R.error("用户名已存在");
//                    }
//                    if(status == -4){
//
//                        return R.error("手机号重复");
//                    }
//                    if(status == -5){
//
//
//                        return R.error("工号重复");
//                    }


                    Departmentteacher departmentteacher = new Departmentteacher();
                    departmentteacher.setTeacherId(Math.toIntExact(teacher.getId()));
                    departmentteacher.setDepartmentId(departmentId);
                    departmentteacherService.create(departmentteacher);

            }



//            return R.success(mapMessage);
            mapMessage.put("message","新增成功");


//            return R.success(mapMessage);
            return  new ResponseEntity<>(HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
//            return "Error importing data: " + e.getMessage();
//            return R.success(e.getMessage());
            return  new ResponseEntity<>(e.getMessage(),HttpStatus.OK);
        }

    }

    @PostMapping("/importClazzStudentExcel")
    public ResponseEntity<Object>  importClazzStudentExcel(@RequestParam("file") MultipartFile file,@RequestParam("clazzId") Integer clazzId) {
        try {
            // 将文件内容读取到字节数组
            byte[] bytes = file.getBytes();
            List<String[]> data = readExcelFromBytes(bytes);
            data.remove(0);
            List<Map<String,Object>> mapList = new ArrayList<>();
            Integer initNumber = 0;

            Map<String,Object> mapMessage = new HashMap<>();

            List<Integer> statusList = new ArrayList<>();

            //验证逻辑
            for(String[] currentArr :data){

                initNumber++;
                Map<String,Object> map = new HashMap<>();
                Student teacher = new Student();
                if(!String.valueOf(currentArr[0]).equals("")){
                    teacher.setNumber(currentArr[0]);
                }

                if(!String.valueOf(currentArr[1]).equals("")){
                    teacher.setName(currentArr[1]);
                }
                if(!String.valueOf(currentArr[1]).equals("")){
                    teacher.setUsername(currentArr[1]);
                }

                if(!String.valueOf(currentArr[2]).equals("")){
                    teacher.setNickName(currentArr[2]);
                }

                if(!String.valueOf(currentArr[3]).equals("")){
                    teacher.setPassword(currentArr[3]);
                }

                if(!String.valueOf(currentArr[4]).equals("")){
                    teacher.setGender(currentArr[4]);
                }

                if(!String.valueOf(currentArr[5]).equals("")){
                    teacher.setPhone(currentArr[5]);
                }

                if(!String.valueOf(currentArr[6]).equals("")){
                    teacher.setEmail(currentArr[6]);
                }


                Map<String,Object> map1 = studentService.checkStudent(teacher);
//                map.put("status",map1.get("status"));

                if(String.valueOf(map1.get("status")).equals("1")){
                    statusList.add((Integer) map1.get("status"));
                }

                mapList.add(map1);
            }
            if(statusList.size()!=0){
                mapMessage.put("message","导入成功,但部分数据错误");
                mapMessage.put("mapList",mapList);
                mapMessage.put("status",1);
//                mapMessage.put("result",data);
//                return R.success(mapMessage);
//                System.out.println("==mapMessage=="+mapMessage);
                return new ResponseEntity<>(mapMessage, HttpStatus.valueOf(401));
            }
//            String[] currentArr :data
            for(int i = 0;i < data.size();i++){


                Student student = new Student();
                student.setNumber(data.get(i)[0]);
                student.setName(data.get(i)[2]);
                student.setUsername(data.get(i)[2]);
                student.setNickName(data.get(i)[1]);
                student.setPassword(data.get(i)[3]);
                student.setGender(data.get(i)[4]);
                student.setPhone(data.get(i)[5]);
                student.setEmail(data.get(i)[6]);
                student.setEnabled(true);
                Integer status = studentService.create(student);


                mapMessage.put("message","导入成功,但部分数据错误");
                mapMessage.put("mapList",mapList);
                mapMessage.put("status",1);
                    if(status == -1){
                        mapMessage.put("status",-1);
                        mapList.get(i).put("emailType","邮箱重复");
                        return  new ResponseEntity<>(mapMessage,HttpStatus.OK);

//                        return R.error("邮箱重复");
                    }
                    if(status == -3){
                        mapMessage.put("status",-3);
                        mapList.get(i).put("nameType","用户名已存在");
                        return  new ResponseEntity<>(mapMessage,HttpStatus.OK);
//                        return R.error("用户名已存在");
                    }
                    if(status == -4){
                        mapMessage.put("status",-4);
                        mapList.get(i).put("phoneType","手机号重复");
                        return  new ResponseEntity<>(mapMessage,HttpStatus.OK);
//                        return R.error("手机号重复");
                    }
                    if(status == -5){
                        mapMessage.put("status",-5);
                        mapList.get(i).put("numberType","工号重复");
                        return  new ResponseEntity<>(mapMessage,HttpStatus.OK);

//                        return R.error("工号重复");
                    }


                Clazzandstudent clazzandstudent = new Clazzandstudent();
                clazzandstudent.setClazzId(Long.valueOf(clazzId));
                clazzandstudent.setStudentId(student.getId());
                if(student.getId()!=null){
                    clazzandstudentService.save(clazzandstudent);
                }


            }



//            return R.success(mapMessage);
            mapMessage.put("message","新增成功");


//            return R.success(mapMessage);
            return  new ResponseEntity<>(HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
//            return "Error importing data: " + e.getMessage();
//            return R.success(e.getMessage());
            return  new ResponseEntity<>(e.getMessage(),HttpStatus.OK);
        }

    }

    public List<String[]> readExcelFromBytes(byte[] bytes) {
        List<String[]> data = new ArrayList<>();
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             Workbook workbook = new XSSFWorkbook(bais)) {
            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                String[] rowData = new String[row.getLastCellNum()];
                for (int i = 0; i < row.getLastCellNum(); i++) {
                    Cell cell = row.getCell(i);
                    if (cell == null) {
                        rowData[i] = "";
                    } else {
                        switch (cell.getCellType()) {
                            case STRING:
                                rowData[i] = cell.getStringCellValue();
                                break;
                            case NUMERIC:
                                rowData[i] = String.valueOf((long) cell.getNumericCellValue());
                                break;
                            case BOOLEAN:
                                rowData[i] = String.valueOf(cell.getBooleanCellValue());
                                break;
                            default:
                                rowData[i] = "";
                        }
                    }
                }
                for(String current :rowData){
                    System.out.println(current);
                }
                data.add(rowData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
}
